<?php

namespace app\controller\admin\info;


use app\BaseController;
use app\common\repositories\info\ArticleRepository as repository;
use think\App;
use think\exception\ValidateException;

class Article extends BaseController
{
    protected $repository;

    public function __construct(App $app, repository $repository)
    {
        parent::__construct($app);
        $this->repository = $repository;
    }

    public function create()
    {
        $data = $this->checkParams();
        $data['type'] = 1;
        $this->repository->create($data);
        return success('添加成功');
    }


    public function update($id)
    {
        $content = $this->repository->get($id);
        if(!$content)
            throw new ValidateException('数据不存在');
        $data = $this->checkParams();
        $content->save($data);
        return success('修改成功');
    }


    public function checkParams()
    {
        $params = $this->request->params(['title','content','avatar']);
        validate([
            'avatar|封面图'=> 'require',
            'title|标题'=>'require|max:250',
            'content|内容'=>'require',
        ])->check($params);
        return $params;
    }


    public function delete($id)
    {
        $data = $this->repository->get($id);
        if($data){
            $data->save(['is_del'=>1]);
        }
        return success('删除成功');
    }


    public function detail($id)
    {
        $content = $this->repository->get($id);
        if(!$content)
            throw new ValidateException('数据不存在');
        return success($content);
    }


    public function lst()
    {

        [$page,$limit] = $this->request->page();

        $query = $this->repository->getSearch()->where('is_del',0);
        $keyword = input('keyword');
        if($keyword !== ''){
            $query = $query->where('title','like',"%{$keyword}%");
        }

        $count = $query->count();
        $list = $query->order('id desc')->page($page,$limit)->select();
        return success(compact('count','list'));
    }
}